package com.yugao.fintech.draper.core.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;

/**
 * FTP上传下载工具类
 */
public class FtpUtil {

	// FTP地址
	private String host = "";

	// 端口号
	private int port;

	// 用户名
	private String username = "";

	// 密码
	private String password = "";

	private FTPClient ftpClient = null;

	/**
	 * 获取ftp连接
	 * @return 连接成功与否 true:成功， false:失败
	 * @throws Exception
	 */
	public FtpUtil(String host, String username, String password) {
		this.host = host;
		this.username = username;
		this.password = password;
	}

	public boolean connect() throws Exception {
		if (ftpClient != null && ftpClient.isConnected()) {
			return true;
		}
		try {
			ftpClient = new FTPClient();
			ftpClient.setControlEncoding("UTF-8");
			// 连接
			ftpClient.connect(this.host, this.port);
			ftpClient.login(this.username, this.password);
			// 检测连接是否成功
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				this.close();
				System.err.println("FTP server refused connection.");
				System.exit(1);
			}
			System.out.println("open FTP success:" + this.host + ";port:" + this.port + ";name:" + this.username
					+ ";pwd:" + this.password);
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii
			return true;
		}
		catch (Exception ex) {
			this.close();
			ex.printStackTrace();
			return false;
		}
	}

	/**
	 * 关闭ftp连接
	 * @throws Exception
	 */
	public void close() throws Exception {
		if (ftpClient != null && ftpClient.isConnected()) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
